package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.statistics;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.GetWeightByMonthBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.StatisticWeightSheetsDayBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.CompanyWeightMoneyNumBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.PeriodStatistics;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.PoundQueryBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CProductsInfo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompanyWeightMoneyNumExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.MonthReportData;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.ProductWeightMoneyNumExportExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICProductsInfoService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetWeightByDayVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.StatisticWeightSheetsDayVo;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.excel.strategy.CustomSheetWriteHandler;
import com.xiaoxu.intranetweb.util.excel.strategy.CustomSheetWriteHandler1;
import com.xiaoxu.intranetweb.util.excel.EasyExcelUtil;
import com.xiaoxu.intranetweb.util.excel.strategy.ExcelFillCellRowMergeStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/poundSheetStatistics")
public class PoundSheetStatisticsController {
    @Autowired
    private CompanyWeightMoneyNumBu companyWeightMoneyNumBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private PoundQueryBu poundQueryBu;
    @Autowired
    private PeriodStatistics periodStatistics;
    @Autowired
    private ICProductsInfoService icProductsInfoService;

    /**
     * 公司重量金额统计
     *
     * @param startTime:   开始时间
     * @param endTime:     结束时间
     * @param coSupply:    供货单位
     * @param coSupplyChi: 供货单位子单位名
     * @param co:          客户单位
     * @param chiCo:       客户单位子单位名
     * @param product:     品种
     * @param truckno:     车号
     * @param operator:    操作员
     * @param sheetno:     单号
     * @param request:     HttpServletRequest
     * @return SzResult
     */
    @GetMapping("/companyWeightMoneyNum")
    public SzResult companyWeightMoneyNum(@RequestParam(value = "startTime", required = false) String startTime,
                                          @RequestParam(value = "endTime", required = false) String endTime,
                                          @RequestParam(value = "coSupply", required = false) String coSupply,
                                          @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
                                          @RequestParam(value = "co", required = false) String co,
                                          @RequestParam(value = "chiCo", required = false) String chiCo,
                                          @RequestParam(value = "pdtClassId", required = false) Integer pdtClassId,
                                          @RequestParam(value = "product", required = false) String product,
                                          @RequestParam(value = "truckno", required = false) String truckno,
                                          @RequestParam(value = "operator", required = false) String operator,
                                          @RequestParam(value = "sheetno", required = false) String sheetno,
                                          @RequestParam(value = "reason", required = false) String reason,
                                          @RequestParam(value = "iccardno", required = false) String iccardno,
                                          @RequestParam(value = "iccardAlias", required = false) String iccardAlias,
                                          @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                          @RequestParam(value = "cpyClass", required = false) String cpyClass,
                                          @RequestParam(value = "pdtClass", required = false) String pdtClass,
                                          HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        List<String> product1 = new ArrayList<>();
        if (product != null && !product.equals("")  ) {
            if ( product.contains(",")) {
                product1 = Stream.of(product.split(",")).collect(Collectors.toList());
            }else{
                product1.add(product);
            }
        }
        return companyWeightMoneyNumBu.getcompanyWeightMoneyNum(startTime, endTime, coSupply, coSupplyChi, co, chiCo, pdtClassId, product1, truckno, iccardno,iccardAlias, isEmpty, cpyClass, pdtClass, token, plantId);
    }

    /**
     * 品种重量金额统计
     *
     * @param coSupply:    供货单位
     * @param coSupplyChi: 供货单位子单位名
     * @param co:          客户单位
     * @param chiCo:       客户单位子单位名
     * @param product:     品种
     * @param truckno:     车号
     * @param request:     HttpServletRequest
     * @return SzResult
     */
    @GetMapping("/productWeightMoneyNum")
    public SzResult productWeightMoneyNum(
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "coSupply", required = false) String coSupply,
            @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
            @RequestParam(value = "co", required = false) String co,
            @RequestParam(value = "chiCo", required = false) String chiCo,
            @RequestParam(value = "pdtClassId", required = false) Integer pdtClassId,
            @RequestParam(value = "product", required = false) String product,
            @RequestParam(value = "truckno", required = false) String truckno,
//            @RequestParam(value = "operator", required = false) String operator,
//            @RequestParam(value = "sheetno", required = false) String sheetno,
//            @RequestParam(value = "reason", required = false) String reason,
            @RequestParam(value = "iccardno", required = false) String iccardno,
            @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
            @RequestParam(value = "cpyClass", required = false) String cpyClass,
            @RequestParam(value = "pdtClass", required = false) String pdtClass,
            @RequestParam(value = "iccardAlias", required = false) String iccardAlias,
            HttpServletRequest request) throws Exception {
        String plantId = request.getHeader("Plant-Id");
        String token = request.getHeader("Authorization");
        List<String> product1 = new ArrayList<>();
        if (product != null && !product.equals("")  ) {
            if ( product.contains(",")) {
                product1 = Stream.of(product.split(",")).collect(Collectors.toList());
            }else{
                product1.add(product);
            }
        }
        return companyWeightMoneyNumBu.getproductWeightMoneyNum(startTime, endTime, coSupply, coSupplyChi, co, chiCo, pdtClassId, product1, truckno, iccardno,iccardAlias, isEmpty, cpyClass, pdtClass, token, plantId);
    }


    @GetMapping("/productWeightMoneyNumByOne")
    public SzResult productWeightMoneyNumByOne(@RequestParam(value = "dateTime", required = false) String dateTime,
                                               @RequestParam(value = "product", required = false) List<String> product,
                                               @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                               @RequestParam(value = "coSupply", required = false) String coSupply,
                                               @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
                                               @RequestParam(value = "co", required = false) String co,
                                               @RequestParam(value = "chiCo", required = false) String chiCo,
                                               @RequestParam(value = "truckno", required = false) String truckno,
                                               @RequestParam(value = "iccardno", required = false) String iccardno,
                                               //startTime
                                               @RequestParam(value = "startTime", required = false) String startTime,
                                               @RequestParam(value = "endTime", required = false) String endTime,
                                               @RequestParam(value = "iccardAlias", required = false) String iccardAlias,
                                               HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        if (dateTime != null && !dateTime.isEmpty()) {
            LocalDate date = LocalDate.parse(dateTime);
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
            startTime = startOfDay.format(formatter).replace("T", " ");
            endTime = endOfDay.format(formatter).replace("T", " ");
        }
        String plantId = request.getHeader("Plant-Id");
        return companyWeightMoneyNumBu.productWeightMoneyNumByOne(startTime, endTime, coSupply, coSupplyChi, co, chiCo, product, truckno, iccardno,iccardAlias, isEmpty, token, plantId);
    }

    //    导出excel
    @PostMapping("/companyWeightMoneyNumExportExcel")
    public void companyWeightMoneyNumExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
    JSONObject form = jsonParam.getObject("form", JSONObject.class);
//     String startTime, String endTime, String coSupply, String co, List<String> product, String truckNo, String iccardno, Integer isEmpty,String cpyClass,String pdtClass
        String startTime = "", endTime = "", coSupply = "", coSupplyChi = "", co = "", chiCo = "", truckNo = "", iccardno = "", cpyClass = "", pdtClass = "",iccardAlias="";
        List<String> product = new ArrayList<>();
        Integer isEmpty = null, pdtClassId = null;
        if (form != null) {
            if (form.get("startTime") != null) {
                startTime = form.getString("startTime");
            }
            if (form.get("endTime") != null) {
                endTime = form.getString("endTime");
            }
            if (form.get("coSupply") != null) {
                coSupply = form.getString("coSupply");
            }
            if (form.get("coSupplyChi") != null) {
                coSupplyChi = form.getString("coSupplyChi");
            }
            if (form.get("co") != null) {
                co = form.getString("co");
            }
            if (form.get("chiCo") != null) {
                chiCo = form.getString("chiCo");
            }
            if (form.get("product") != null) {
             product = JSON.parseObject(form.get("product").toString(), new TypeReference<List<String>>() {});
            }
            if (form.get("truckNo") != null) {
                truckNo = form.getString("truckNo");
            }
//       pdtClassId
            if (form.get("pdtClassId") != null) {
                pdtClassId = Integer.parseInt(form.getString("pdtClassId"));
            }
//        isEmpty
            if (form.get("isEmpty") != null) {
                isEmpty = Integer.parseInt(form.getString("isEmpty"));
            }
            if (form.get("iccardno") != null) {
                iccardno = form.getString("iccardno");
            }
            if (form.get("iccardAlias") != null) {
                iccardAlias = form.getString("iccardAlias");
            }
            if (form.get("cpyClass") != null) {
                cpyClass = form.getString("cpyClass");
            }
            if (form.get("pdtClass") != null) {
                pdtClass = form.getString("pdtClass");
            }
        }
        String plantId = request.getHeader("Plant-Id");
        Future<List<CompanyWeightMoneyNumExcelEn>> listFuture = companyWeightMoneyNumBu.companyWeightMoneyNumExportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, startTime, endTime, coSupply, coSupplyChi, co, chiCo, pdtClassId, product, truckNo, iccardno,iccardAlias, isEmpty, cpyClass, pdtClass, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CompanyWeightMoneyNumExcelEn> companyWeightMoneyNumExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "月度统计（按单位）";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompanyWeightMoneyNumExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("月度统计（按单位）")
                .doWrite(companyWeightMoneyNumExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    /**
     * 导表
     */

    @PostMapping("productWeightMoneyNumExportExcel")
    public void productWeightMoneyNumExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = null;
        if (token != null) {
            plantId = request.getHeader("Plant-Id");
        }


        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        JSONObject form = jsonParam.getObject("form", JSONObject.class);
//     String startTime, String endTime, String coSupply, String co, List<String> product, String truckNo, String iccardno, Integer isEmpty,String cpyClass,String pdtClass
        String startTime = "", endTime = "", coSupply = "", coSupplyChi = "", co = "", chiCo = "", truckNo = "", iccardno = "", cpyClass = "", pdtClass = "",iccardAlias="";
        List<String> product = new ArrayList<>();
        Integer isEmpty = null, pdtClassId = null;
        if (form != null) {
            if (form.get("startTime") != null) {
                startTime = form.getString("startTime");
            }
            if (form.get("endTime") != null) {
                endTime = form.getString("endTime");
            }
            if (form.get("coSupply") != null) {
                coSupply = form.getString("coSupply");
            }
            if (form.get("coSupplyChi") != null) {
                coSupplyChi = form.getString("coSupplyChi");
            }
            if (form.get("co") != null) {
                co = form.getString("co");
            }
            if (form.get("chiCo") != null) {
                chiCo = form.getString("chiCo");
            }
            if (form.get("product") != null) {
                product = JSON.parseObject(form.get("product").toString(), new TypeReference<List<String>>() {});
            }
            if (form.get("truckNo") != null) {
                truckNo = form.getString("truckNo");
            }
//       pdtClassId
            if (form.get("pdtClassId") != null) {
                pdtClassId = Integer.parseInt(form.getString("pdtClassId"));
            }
//        isEmpty
            if (form.get("isEmpty") != null) {
                isEmpty = Integer.parseInt(form.getString("isEmpty"));
            }
            if (form.get("iccardno") != null) {
                iccardno = form.getString("iccardno");
            }
            if (form.get("iccardAlias") != null) {
                iccardAlias = form.getString("iccardAlias");
            }
            if (form.get("cpyClass") != null) {
                cpyClass = form.getString("cpyClass");
            }
            if (form.get("pdtClass") != null) {
                pdtClass = form.getString("pdtClass");
            }
        }

        Future<List<ProductWeightMoneyNumExportExcelEn>> listFuture = companyWeightMoneyNumBu.productWeightMoneyNumExportExcel(fields, ids, filename, isHeader, mode, original, pager, pdtClassId, product, startTime, endTime, truckNo, iccardno, sheetName, response, plantId, coSupply, coSupplyChi, co, chiCo,isEmpty);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<ProductWeightMoneyNumExportExcelEn> productWeightMoneyNumExportExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "按品种";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ProductWeightMoneyNumExportExcelEn.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("按品种").doWrite(productWeightMoneyNumExportExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    //查询每月的各品种销售情况
    @GetMapping("/getMonthSale")
    public SzResult getMonthSale(@RequestParam("year") Integer year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return poundQueryBu.getMonthSale(year, token, plantId);
    }

    @PostMapping("/getWeightByDay")
    public SzResult getWeightByDay(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String company = jsonParam.getString("company");
        String data = jsonParam.getString("data");
        String plantId = jsonParam.getString("plantId");
        String pdtInfStockcls = jsonParam.getString("pdtInfStockcls");
        String myPlantId = request.getHeader("Plant-Id");
        return companyWeightMoneyNumBu.getWeightByDay(company, data, plantId, pdtInfStockcls, token, myPlantId);
    }

    //    经营日报
    //    经营日报
    @GetMapping("/dailyReport")
    public SzResult dailyReport(@RequestParam(value = "date", required = false) String date, @RequestParam(value = "plantId", required = false) String plantId, @RequestParam(value = "pdtInfStockcls", required = false) Integer pdtInfStockcls, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        if (plantId == null) {
            plantId = request.getHeader("Plant-Id");
        }
        StatisticWeightSheetsDayBo params = new StatisticWeightSheetsDayBo();
        params.setPlantId(plantId);
        params.setDate(date);
//        params.setPdtInfStockcls(pdtInfStockcls);
        if (pdtInfStockcls != null) {
            QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PDTINF_STOCKCLS", pdtInfStockcls);
            queryWrapper.eq("DATA_FROM", plantId);
            List<CProductsInfo> list = icProductsInfoService.list(queryWrapper);
            List<String> pdtName = new ArrayList<>();
            for (CProductsInfo cProductsInfo : list) {
                pdtName.add(cProductsInfo.getPdtinfPdt());
                params.setPdtName(pdtName);
            }
        }
        List<StatisticWeightSheetsDayVo> sortedList = periodStatistics.weightSheetsDay(params);
        Map<String, Object> map = new HashMap<>();
        map.put("total", sortedList.size());
        map.put("list", sortedList);
        return SzResult.success(map);
    }

    //    导出经营日报
    @PostMapping("/dailyReportExport")
    public void dailyReportExport(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        Map form = jsonParam.getObject("form", Map.class);
        String date = null;
        if (form.get("date") != null && !form.get("date").equals("null")) {
            date = form.get("date").toString();
        }
        String plantId = null;
        if (form.get("plantId") != null && !form.get("plantId").equals("null")) {
            plantId = form.get("plantId").toString();
        }
        String token = request.getHeader("Authorization");

        if (plantId == null) {
            plantId = request.getHeader("Plant-Id");
        }
        Integer pdtInfStockcls = null;
        if (form.get("pdtInfStockcls") != null && !form.get("pdtInfStockcls").equals("null")) {
            pdtInfStockcls = Integer.parseInt(form.get("pdtInfStockcls").toString());
        }
        StatisticWeightSheetsDayBo params = new StatisticWeightSheetsDayBo();
        params.setPlantId(plantId);
        params.setDate(date);
        if (pdtInfStockcls != null) {
            QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PDTINF_STOCKCLS", pdtInfStockcls);
            queryWrapper.eq("DATA_FROM", plantId);
            List<CProductsInfo> list = icProductsInfoService.list(queryWrapper);
            List<String> pdtName = new ArrayList<>();
            for (CProductsInfo cProductsInfo : list) {
                pdtName.add(cProductsInfo.getPdtinfPdt());
                params.setPdtName(pdtName);
            }
        }
        List<StatisticWeightSheetsDayVo> sortedList = periodStatistics.weightSheetsDay(params);

        String filename = "经营日报" + date;
        List<List<String>> header = new ArrayList<>();
        header.add(Arrays.asList(filename, "厂名"));
        header.add(Arrays.asList(filename, "品类"));
        header.add(Arrays.asList(filename, "品种"));
        header.add(Arrays.asList(filename, "日均价"));
        header.add(Arrays.asList(filename, "日销量"));
        header.add(Arrays.asList(filename, "日销额"));
        header.add(Arrays.asList(filename, "月销量"));
        header.add(Arrays.asList(filename, "月销额"));
        header.add(Arrays.asList(filename, "年销量"));
        header.add(Arrays.asList(filename, "年销额"));
        try {
//            从第几行开始合并
            int mergeRowIndex = 2;
//            哪几列需要做合并
            int[] mergeColumnIndex = {0, 1};
            WriteCellStyle writeCellStyle = new WriteCellStyle();
//居中
            writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            writeCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(writeCellStyle, writeCellStyle);
            ExcelFillCellRowMergeStrategy excelFillCellRowMergeStrategy = new ExcelFillCellRowMergeStrategy(mergeRowIndex, mergeColumnIndex);
            List<CellWriteHandler> cellWriteHandlerList = Stream.of(excelFillCellRowMergeStrategy).collect(Collectors.toList());
            EasyExcelUtil.writeExcelMerge(response.getOutputStream(), null, sortedList, header, filename, cellWriteHandlerList, horizontalCellStyleStrategy);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 月报导表
     */

    @PostMapping("/monthReportExport")
    public void monthReportExport(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        // 解析请求参数
        Map<String, Object> form = jsonParam.getObject("form", Map.class);
        String company = (String) form.getOrDefault("company", "");
        String data = (String) form.getOrDefault("data", "");
        String plantId = (String) form.getOrDefault("plantId", "");
        String pdtInfStockcls = (String) form.getOrDefault("pdtInfStockcls", "");
        String token = request.getHeader("Authorization");
        String myPlantId = request.getHeader("My-Plant-Id");

        // 获取按天的数据
        List<GetWeightByDayVo> resultList = companyWeightMoneyNumBu.getWeightByDayExcel(company, data, plantId, pdtInfStockcls, token, myPlantId);

        // 将数据转换为MonthReportData格式
        List<MonthReportData> reportDataList = convertToReportData(resultList);


// 设置响应头
        String filename = data+"月报";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");

// 导出 Excel
        EasyExcel.write(response.getOutputStream(), MonthReportData.class)
                .sheet(data+"月报")
                .doWrite(reportDataList);

// 清理资源
        try {
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 将数据转换为 MonthReportData 格式的方法
// 将数据转换为 MonthReportData 格式的方法

    private List<MonthReportData> convertToReportData(List<GetWeightByDayVo> dataList) {
        Map<String, MonthReportData> reportDataMap = new HashMap<>();

        for (GetWeightByDayVo data : dataList) {
            String key = data.getCompany() + "_" + data.getProduct();
            MonthReportData reportData = reportDataMap.getOrDefault(key, new MonthReportData());

            // 设置单位名称和产品
            reportData.setCompany(data.getCompany());
            reportData.setProduct(data.getProduct());

            // 设置月累积量和月累计销售额
            reportData.setTotalQuantity(new BigDecimal(data.getTotalNumber()));
            reportData.setTotalSales(new BigDecimal(data.getTotalMoney()));

            // 从日期字符串中提取日部分
            LocalDate date = LocalDate.parse(data.getData(), DateTimeFormatter.ISO_LOCAL_DATE);
            int day = date.getDayOfMonth();

            // 根据日期填充每日的数据
            if (day >= 1 && day <= 31) {
                // 如果当前天数的数据不为0，则设置
                if (!new BigDecimal(data.getNumber()).equals(BigDecimal.ZERO)) {
                    reportData.setDayQuantity(day, new BigDecimal(data.getNumber()));
                }
                if (!new BigDecimal(data.getUnitPrice()).equals(BigDecimal.ZERO)) {
                    reportData.setDayUnitPrice(day, new BigDecimal(data.getUnitPrice()));
                }
                if (!new BigDecimal(data.getMoney()).equals(BigDecimal.ZERO)) {
                    reportData.setDayAmount(day, new BigDecimal(data.getMoney()));
                }
            }

            reportDataMap.put(key, reportData);
        }

        // 将 Map 转换为列表
        List<MonthReportData> reportDataList = new ArrayList<>(reportDataMap.values());

        // 按产品排序
        reportDataList.sort(Comparator.comparing(MonthReportData::getProduct));

        // 为每个产品生成一个小计行
        List<MonthReportData> finalList = new ArrayList<>();
        String currentProduct = null;
        MonthReportData subTotal = null;

        for (MonthReportData reportData : reportDataList) {
            if (currentProduct == null || !currentProduct.equals(reportData.getProduct())) {
                if (subTotal != null) {
                    finalList.add(subTotal);
                }
                currentProduct = reportData.getProduct();
                subTotal = new MonthReportData();
                subTotal.setCompany("小计");
                subTotal.setProduct(currentProduct);
            }

            // 累加小计
            subTotal.setTotalQuantity(subTotal.getTotalQuantity().add(reportData.getTotalQuantity()));
            subTotal.setTotalSales(subTotal.getTotalSales().add(reportData.getTotalSales()));
            for (int i = 0; i < 31; i++) {
                subTotal.setDayQuantity(i + 1, subTotal.getDayQuantity(i + 1).add(reportData.getDayQuantity(i + 1)));
                subTotal.setDayUnitPrice(i + 1, subTotal.getDayUnitPrice(i + 1).add(reportData.getDayUnitPrice(i + 1)));
                subTotal.setDayAmount(i + 1, subTotal.getDayAmount(i + 1).add(reportData.getDayAmount(i + 1)));
            }

            finalList.add(reportData);
        }

        // 添加最后一个产品的小计行
        if (subTotal != null) {
            finalList.add(subTotal);
        }

        // 添加合计行
        MonthReportData totalRow = new MonthReportData();
        totalRow.setCompany("合计");
        totalRow.setProduct("");
        for (MonthReportData reportData : reportDataList) {
            totalRow.setTotalQuantity(totalRow.getTotalQuantity().add(reportData.getTotalQuantity()));
            totalRow.setTotalSales(totalRow.getTotalSales().add(reportData.getTotalSales()));
            for (int i = 0; i < 31; i++) {
                totalRow.setDayQuantity(i + 1, totalRow.getDayQuantity(i + 1).add(reportData.getDayQuantity(i + 1)));
                totalRow.setDayUnitPrice(i + 1, totalRow.getDayUnitPrice(i + 1).add(reportData.getDayUnitPrice(i + 1)));
                totalRow.setDayAmount(i + 1, totalRow.getDayAmount(i + 1).add(reportData.getDayAmount(i + 1)));
            }
        }
        finalList.add(totalRow);

        return finalList;
    }

}